#include "userMysql.h"
#include"mainwindow.h"
Q_GLOBAL_STATIC(userMysql,theInstance);
userMysql::userMysql()
{
      connect();
}

userMysql::~userMysql()
{

}

userMysql *userMysql::instance()
{
    return theInstance();
}

void userMysql::connect()
{

    database=QSqlDatabase::addDatabase("QMYSQL","main");//连接mysql数据库，连接名为main
    database.setDatabaseName("projectdata");//设置要连接的数据库名称
    database.setHostName("localhost");//设置主机名称
    database.setUserName("root");//设置用户名称
    database.setPassword("zxc20021102");//设置用户密码
    if(database.open())
    {
        QMessageBox::information(nullptr,"linking","Connect MySQL succeed",QMessageBox::Yes);
    }
    else{

        QMessageBox::information(nullptr,"linking","Connect MySQL failed",QMessageBox::Cancel);
    }










}

bool userMysql::getUserData(QVector<UserInfo> &users)
{


    QSqlQueryModel sql;

    sql.setQuery("select *from userInfo",database);
    int row=sql.rowCount();
    if(row<0)
    {
        QMessageBox::information(nullptr,"SELECT","没有查询到相关记录",QMessageBox::Yes);
        return false;
    }
    qDebug()<<row;


    for(int i=0;i<row;i++)
    {
        QString accountNumber;
        QString userName;
        int userType;
        QString password;
        UserInfo demo;
        for(int j=0;j<5;j++)
        {
            QModelIndex index=sql.index(i,j);
            if(j==0)
                demo.id=sql.data(index).toInt();
            else if(j==1)
                demo.accountNumber=sql.data(index).toString();
            else if(j==2)
                demo.userName=sql.data(index).toString();
            else if(j==3)
                demo.userType=sql.data(index).toInt();
            else
                demo.userPassword=sql.data(index).toString();


        }

        qDebug()<<demo.id<<" "<<demo.accountNumber<<""<<demo.userName<<" "<<demo.userType<<" "<<demo.userPassword<<endl;
//        //清空上次的内容；
//        userName="";
//        userType=0;
//        password="";
         users.push_back(demo);





    }



return true;



}

bool userMysql::saveUserData(UserInfo &user)
{

    QVector<UserInfo>demo;
    getUserData(demo);
    int count=demo.count();
    qDebug()<<"count->"<<count<<endl;
    // QStringList userNameList;
    QStringList accountNumberList;
    //for(int i=0;i<count;i++)
    //{
    //    userNameList.append(demo[i].userName);
    //    qDebug()<<userNameList[i];
    //}
    for(int i=0;i<count;i++)
    {
        accountNumberList.append(demo[i].accountNumber);
        qDebug()<<accountNumberList[i]<<" ";
    }
    //bool ok=userNameList.contains(user.userName);
    bool ok=accountNumberList.contains(user.accountNumber);
    if(!ok)
    {
        if(user.accountNumber!=""&&user.userName!=""&&user.userPassword!="")
        {
            QSqlQuery query(database);
            query.prepare("INSERT INTO userinfo (accountNumber,userName, userType, userPassword) "
                          "VALUES (:accountNumber,:userName, :userType, :userPassword)");
            query.bindValue(":accountNumber",user.accountNumber);
            query.bindValue(":userName", user.userName);
            query.bindValue(":userType", user.userType);
            query.bindValue(":userPassword", user.userPassword);
            if (!query.exec())
            {
                qDebug() << "插入数据失败：" <<query.lastError().text();
//                QMessageBox msgBox;
//                msgBox.setStandardButtons(QMessageBox::Yes );
//                msgBox.setWindowTitle("Tip");
//                msgBox.setText("用户注册失败！");
//                msgBox.button(QMessageBox::Yes)->setText("确定");
//                msgBox.exec();
//                QMessageBox::information(this,"tip",   "删除用户成功" );
                return false;

            }
            else
            {
                qDebug() << "用户注册成功！";
                QMessageBox msgBox;
                msgBox.setStandardButtons(QMessageBox::Yes );
                msgBox.setWindowTitle("Tip");
                msgBox.setText("用户注册成功！");

                msgBox.button(QMessageBox::Yes)->setText("确定");
                msgBox.exec();
                return true;
            }



        }
        else
        {
            QMessageBox msgBox;
            msgBox.setStandardButtons(QMessageBox::Yes );
            msgBox.setWindowTitle("Tip");
            msgBox.setText("账号、用户名、和密码都不能为空！");
            msgBox.button(QMessageBox::Yes)->setText("确定");
            msgBox.exec();

            qDebug()<<"账号、用户名、和密码不能为空"  <<endl;
            return false;

        }

    }
    else
    {
        QMessageBox msgBox;
        msgBox.setStandardButtons(QMessageBox::Yes );
        msgBox.setWindowTitle("Tip");
        msgBox.setText("该账号已被注册！");
        msgBox.button(QMessageBox::Yes)->setText("确定");
        msgBox.exec();
        qDebug()<<"该账号已被注册！";
//        emit clearRegisterInformation();
        RegisteredUserInformation ::instance()->ClearLineEdit();
        return false;
    }





}

bool userMysql::saveSensorData(sensorData &data)
{

    QSqlQuery query(database);
    query.prepare("INSERT INTO sensordata (Time, AirTemperature, AirHumidity,LightIntensity,CO2Concentration,SoilMoisture) "
                  "VALUES (:Time, :AirTemperature, :AirHumidity,:LightIntensity,:CO2Concentration,:SoilMoisture)");
    query.bindValue(":Time", data.Time);
    query.bindValue(":AirTemperature", data.AirTemperature);
    query.bindValue(":AirHumidity", data.AirHumidity);
    query.bindValue(":LightIntensity", data.LightIntensity);
    query.bindValue(":CO2Concentration", data.CO2Concentration);
    query.bindValue(":SoilMoisture", data.SoilMoisture);
    if (!query.exec())
    {
        qDebug() << "插入sensorData数据失败：" <<query.lastError().text();
        return false;

    }
    else
    {
        qDebug() << "sensorData数据插入成功！";
        return true;
    }










}

bool userMysql::deleteUserData(const int id)
{
    qDebug()<<"删除-----ok";
    bool deleteSuccess = false;

    // 使用事务确保操作原子性
    QSqlDatabase::database().transaction();
    QSqlQuery query(database);
    query.prepare("DELETE FROM userinfo WHERE id = ?");
    //query.bindValue(":id", id);
    query.addBindValue(id);

    if (query.exec())
    {
        if (query.numRowsAffected() > 0)
        {
            QSqlDatabase::database().commit();
            deleteSuccess= true;
            qDebug()<<"删除成功mysql";

            return deleteSuccess;
        }
        else
        {
            QSqlDatabase::database().rollback();

            qDebug() << "未找到匹配的数据";
            return deleteSuccess;

        }
    }
    else
    {
        QSqlDatabase::database().rollback();
        qDebug() << "删除失败：" << query.lastError().text();
        return deleteSuccess;


    }

}

int userMysql::changeUserInformation(const UserInfo &Data)
{
    QSqlQuery query(database);
    query .prepare("UPDATE userinfo SET UserName = :userName, userPassword = :userPassword WHERE id = :id");
    // 绑定参数值
    query.bindValue(":userName", Data.userName);
    query.bindValue(":userPassword", Data.userPassword);
    query.bindValue(":id", Data.id);

    // 执行更新
    if (!query.exec())
    {
        qDebug() << "更新失败：" << query.lastError().text();
        return -1;
    }

    // 检查是否实际影响了行（确保存在对应 id）
    if (query.numRowsAffected() <= 0)
    {
        qDebug() << "未找到 ID 为" << Data.id << "的记录";
        return 0;
    }

    return 1;
    qDebug() << "更新成功！";
}
